package com.ylzinfo.channelclient;

import com.ylzinfo.channelclient.config.HttpConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.TimeUnit;

/**
 * 启动类
 * @author zengjw
 */
@Slf4j
@SpringBootApplication
public class ChannelClientApplication {
    @Autowired
    private HttpConfig httpConfig;

    public static void main(String[] args) {
        SpringApplication.run(ChannelClientApplication.class, args);
    }

    @Primary
    @Bean
    OkHttpClient defaultBaseOkHttpClient() {
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(httpConfig.getMaxRequests());
        dispatcher.setMaxRequestsPerHost(httpConfig.getMaxRequestsPerHost());

        return new OkHttpClient.Builder()
                .readTimeout(httpConfig.getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(httpConfig.getWriteTimeout(), TimeUnit.SECONDS)
                .connectTimeout(httpConfig.getConnectTimeout(), TimeUnit.SECONDS)
                .dispatcher(dispatcher)
                .connectionPool(new ConnectionPool(httpConfig.getMaxIdleConnections(), httpConfig.getKeepAliveDuration(), TimeUnit.MINUTES))
                .addInterceptor(chain -> {
                    log.info("=======使用自定义HttpClientBuilder构建的OkHttpClient=====");
                    return chain.proceed(chain.request());
                })
                .build();
    }
}
